public with sharing class cbAutomation {
    //This class, tied to vf page cb automation, automates one of the steps to make the chatterbot work correctly in the sdo.
    
    public cbAutomation(){}
    
    public pageReference doWork(){
        string emailSource = [select email from User where id = :UserInfo.getUserID()].email;
        //build static list of users to affect
        
        //create items within the email service for them
        List<EmailServicesAddress> esaList = [select id, runAsUserID, localpart, emailDomainName from EmailServicesAddress where function.functionName = 'ChatterBot'];     
        string userIDList = '';
        for(EmailServicesAddress esa : esaList)
        {
            userIDList += string.valueOf(esa.RunAsUserID).substring(0,string.valueOf(esa.RunAsUserId).length()-3) + '\',\'';
        }
        userIDList = userIDList.substring(0, userIDList.length()-3);
        string query = 'select id from User where id in (\'' + userIDList + '\')';
        //List<User> uList = [select id from User where id in (:userIDList)];
        List<User> uList = database.query(query);
        
        //get the email addresses provided, attach to the user elements
        for(EmailServicesAddress esa : esaList)
        {
            for(User u : uList)
            {
                if (u.id == esa.runAsUserID)
                {
                    u.email_to_Salesforce_address__c = esa.localPart + '@' + esa.EmailDomainName;
                }
            }
        }
        update uList;
        //accept praise and cash
        
        //system.assert(false, emailSource +','+ query+',<br/>'+ esaList.size()+','+uList.size());
        
        return new PageReference('/apex/chatter');
    }
}